<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>积分答题</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <link rel="stylesheet" href="style.css" />
    <script src="https://g.alicdn.com/dingding/dingtalk-jsapi/3.1.0/dingtalk.open.js"></script>
    <script src='https://g.alicdn.com/code/npm/@ali/dingtalk-h5-remote-debug/0.1.3/index.js'></script>
</head>
<body>
    <div class="header">
        <button class="mobile-menu-btn"><i class="fas fa-bars"></i></button>
        <div class="logo">积分答题</div>
        <div style="flex:1"></div>
    </div>

    <div class="main-content">
        <!-- 积分答题列表页面 -->
        <div id="quiz-page" class="page-container active">
            <h2 class="card-title">积分答题</h2>
            <p style="margin-bottom: 24px; color: #595959;">参与答题获取积分，每答对一题可获得相应积分，累计积分可兑换丰厚奖励</p>
            <div class="quiz-list" id="quiz-item-list"></div>
        </div>

        <!-- 积分答题详情页面 -->
        <div id="quiz-detail-page" class="page-container" style="display: none;">
            <div class="quiz-detail-header">
                <button id="quiz-back-btn" class="btn">返回</button>
                <div class="quiz-progress">
                    <div class="quiz-progress-bar" id="quiz-progress-bar" style="width:0%;"></div>
                </div>
                <div class="quiz-progress-text" id="quiz-progress-text">0/0</div>
            </div>

            <div id="quiz-detail-title" class="card-title" style="margin-top:16px;">问卷</div>
            <div id="quiz-questions-container" class="quiz-questions-container"></div>

            <div class="quiz-detail-actions" style="margin-top:16px; display:flex; gap:12px;">
                <button id="quiz-submit-btn" class="btn btn-primary">提交</button>
                <button id="quiz-cancel-btn" class="btn">取消</button>
            </div>
        </div>

        <!-- 提交成功页面 -->
        <div id="quiz-success-page" class="page-container" style="display: none; text-align: center; padding: 24px;">
            <div style="font-size:56px; color:#52c41a; margin: 8px 0 12px; line-height:1; display:inline-block; overflow:visible;"><i class="fa-solid fa-circle-check"></i></div>
            <h2 class="card-title" style="margin-bottom:12px;">提交成功</h2>
            <div id="success-score" style="margin-bottom:8px; font-size:16px; color:#333;"></div>
            <div id="success-time" style="margin-bottom:16px; font-size:14px; color:#595959;"></div>
            <div style="margin-bottom:16px; color:#8c8c8c;">将在 <span id="success-countdown">3</span> 秒后返回主页</div>
            <button id="success-back-btn" class="btn">立即返回</button>
        </div>
    </div>

    <script>
    // 基础配置
    // 配置后端接口基础路径
    const 线下 = "http://localhost:3100/jeecgboot"
    const 线上 = "/api"
    const API_BASE_URL = 线上;
    
    // ============== 用户信息本地缓存（与 index 同步策略） ==============
    const USER_CACHE_KEY = 'gxd_user_center_data';
    const USER_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 1 周

    function getCachedUserCenterData () {
        try {
            const raw = localStorage.getItem(USER_CACHE_KEY);
            if (!raw) return null;
            const wrapped = JSON.parse(raw);
            if (!wrapped || !wrapped.data || !wrapped.ts) return null;
            if (Date.now() - wrapped.ts > USER_CACHE_TTL_MS) {
                localStorage.removeItem(USER_CACHE_KEY);
                return null;
            }
            return wrapped.data;
        } catch (e) {
            return null;
        }
    }

    function setCachedUserCenterData (data) {
        try {
            localStorage.setItem(USER_CACHE_KEY, JSON.stringify({ data, ts: Date.now() }));
        } catch (e) {
            // ignore
        }
    }

    async function ensureUserInfo () {
        // 1) 先尝试读取缓存
        const cached = getCachedUserCenterData();
        if (cached) {
            window.userCenterData = cached;
            return cached;
        }
        // 2) 无缓存时，若存在钉钉 JSAPI，则走授权换取用户信息
        if (typeof dd !== 'undefined' && dd && typeof dd.ready === 'function') {
            try {
                await new Promise((resolve) => dd.ready(resolve));
                const auth = await new Promise((resolve, reject) => {
                    dd.runtime.permission.requestAuthCode({
                        corpId: "ding60ca55316ff60640f5bf40eda33b7ba0",
                        onSuccess: res => resolve(res),
                        onFail: err => reject(err)
                    });
                });
                const code = auth.code;
                const resp = await fetch(API_BASE_URL + '/dingTalkV2/getUserInfo?code=' + code, {
                    method: 'GET',
                    credentials: 'include'
                });
                const data = await resp.json();
                if (data && data.success) {
                    window.userCenterData = data.result;
                    setCachedUserCenterData(data.result);
                    return data.result;
                }
            } catch (e) {
                // 授权或请求失败则继续兜底
            }
        }
        // 3) 兜底返回空对象（允许通过 URL 参数 uid/uname 提交）
        window.userCenterData = window.userCenterData || {};
        return window.userCenterData;
    }
    // 计时：进入详情时记录开始时间（毫秒）
    let quizStartTimestamp = null;
    // 当前问卷ID（questionTypeId）
    let currentQuestionTypeId = null;

    // 获取用户信息：优先 window.userCenterData（ensureUserInfo 已保证设置）；缺失时用 URL 参数兜底
    function getUserInfo() {
        try {
            const ctx = (typeof window !== 'undefined' && window.userCenterData) || {};
            const ctxUserId = ctx.userid || ctx.userId || '';
            const ctxUserName = ctx.name || ctx.username || '';
            if (ctxUserId && ctxUserName) {
                return { userId: ctxUserId, userName: ctxUserName };
            }
            const sp = new URLSearchParams(location.search);
            return {
                userId: ctxUserId || (sp.get('uid') || ''),
                userName: ctxUserName || (sp.get('uname') || '')
            };
        } catch (e) {
            return { userId: '', userName: '' };
        }
    }

    document.addEventListener('DOMContentLoaded', async function() {
        // 确保优先拿到用户信息（缓存或钉钉）
        await ensureUserInfo();
        const pid = new URLSearchParams(location.search).get('pid');
        if (pid) {
            // 直接进入详情
            showPage('quiz-detail-page');
            loadQuizDetails(pid, '');
        } else {
            // 展示列表
            showPage('quiz-page');
            // initQuizList();
        }
    });

    // 列表：获取与渲染
    // function initQuizList() {
    //     const sp = new URLSearchParams(location.search);
    //     const userId = (((typeof userCenterData !== 'undefined' && userCenterData) && (userCenterData.userid || userCenterData.userId)) || sp.get('uid') || '');
    //     const listUrl = API_BASE_URL + '/hr/dtQuestion/titleList?userId=' + encodeURIComponent(userId);
    //     fetch(listUrl, {
    //         method: 'GET',
    //         credentials: 'include'
    //     })
    //       .then(res => res.json())
    //       .then(data => {
    //           if (data.success && data.result && Array.isArray(data.result.records)) {
    //               renderQuizList(data.result.records);
    //           } else {
    //               renderQuizList([]);
    //           }
    //       })
    //       .catch(() => renderQuizList([]));
    // }

    function renderQuizList(list) {
        const container = document.getElementById('quiz-item-list');
        if (!container) return;
        container.innerHTML = '';
        if (!list || list.length === 0) {
            container.innerHTML = '<div style="text-align:center; padding:40px; color:#999;">暂无可用答题</div>';
            return;
        }
        list.forEach(item => {
            const div = document.createElement('div');
            div.className = 'quiz-card';
            // 根据时间和enable字段判断状态
            const now = new Date();
            const startTimeDate = new Date(item.startTime);
            const endTimeDate = new Date(item.endTime);
            const startTime = item.startTime ? String(item.startTime) : '未知';
            const endTime = item.endTime ? String(item.endTime) : '未知';
            const isAnswered = item.isAnswer === 1 || item.isAnswer === '1';

            let buttonText = '开始答题';
            let buttonClass = 'btn btn-primary btn-block';
            let isEnabled = false;
            
            // 优先“已作答”
            if (isAnswered) {
                buttonText = '已作答';
                buttonClass = 'btn btn-secondary btn-block';
            } else if (item.enable !== '1' && item.enable !== 1) {
                buttonText = '暂未开放';
                buttonClass = 'btn btn-secondary btn-block';
            } else if (now < startTimeDate) {
                buttonText = '暂未开放';
                buttonClass = 'btn btn-secondary btn-block';
            } else if (now > endTimeDate) {
                buttonText = '已结束';
                buttonClass = 'btn btn-ended btn-block';
            } else {
                buttonText = '开始答题';
                buttonClass = 'btn btn-primary btn-block';
                isEnabled = true;
            }
            
            // 为不可用按钮添加提示信息
            let tooltip = '';
            if (!isEnabled) {
                if (isAnswered) {
                    tooltip = '您已作答';
                } else if (item.enable !== '1' && item.enable !== 1) {
                    tooltip = '该答题暂未开放';
                } else if (now < startTimeDate) {
                    tooltip = `答题将于 ${startTime} 开始`;
                } else if (now > endTimeDate) {
                    tooltip = `答题已于 ${endTime} 结束`;
                }
            }
            div.innerHTML = `
                <div class="quiz-title">${item.title || '未命名答题'}</div>
                <div class="quiz-meta">
                    <div>开始时间: ${startTime}</div>
                    <div>结束时间: ${endTime}</div>
                    <div>题目数量: ${item.total || 0}题</div>
                </div>
                <div class="quiz-points">可获得积分: <span class="point-gain">${item.integral || 0}</span></div>
                <button class="${buttonClass}" data-id="${item.id}" ${!isEnabled ? 'disabled' : ''} ${tooltip ? `data-tooltip="${tooltip}"` : ''}>${buttonText}</button>
            `;
            container.appendChild(div);
        });
        bindQuizListEvents();
    }

    function bindQuizListEvents() {
        const buttons = document.querySelectorAll('#quiz-item-list .btn[data-id]');
        buttons.forEach(btn => {
            btn.addEventListener('click', function() {
                if (this.disabled) return;
                const id = this.getAttribute('data-id');
                const title = this.closest('.quiz-card')?.querySelector('.quiz-title')?.textContent || '问卷';
                loadQuizDetails(id, title);
            });
        });
    }

    // 详情：获取与渲染
    function loadQuizDetails(mainId, title) {
        const { userId } = getUserInfo();
        const url = API_BASE_URL + '/hr/dtQuestion/questionList/' + encodeURIComponent(mainId) + (userId ? ('?userId=' + encodeURIComponent(userId)) : '');
        const container = document.getElementById('quiz-questions-container');
        if (container) container.innerHTML = '<div style="padding:24px; text-align:center; color:#999;">加载中...</div>';
        const titleEl = document.getElementById('quiz-detail-title');
        if (titleEl) titleEl.textContent = title || '问卷';
        // 记录当前问卷ID用于提交
        currentQuestionTypeId = mainId;

        fetch(url, { method: 'GET', credentials: 'include' })
          .then(res => res.json())
          .then(data => {
              if (data && data.success === false) {
                  // 若后端返回已作答或其它错误信息，弹出 message
                  if (data.message) {
                      alert(data.message);
                  }
                  // 返回列表页
                  window.location.href = 'index.html';
                  return;
              }
              if (data.success && data.result && Array.isArray(data.result.records)) {
                  const questions = [...data.result.records].sort((a,b) => (a.sort || 0) - (b.sort || 0));
                  renderQuizDetail(questions);
                  showPage('quiz-detail-page');
              } else {
                  if (container) container.innerHTML = '<div style="padding:24px; text-align:center; color:#ff4d4f;">加载失败</div>';
              }
          })
          .catch(() => {
              if (container) container.innerHTML = '<div style="padding:24px; text-align:center; color:#ff4d4f;">请求异常</div>';
          });
    }

    function renderQuizDetail(questions) {
        const container = document.getElementById('quiz-questions-container');
        if (!container) return;
        container.innerHTML = '';
        const total = questions.length;
        updateQuizProgress(0, total);
        questions.forEach((q, idx) => {
            // 根据新接口的type字段判断题目类型
            // type: 1=单选, 2=判断, 3=多选
            const questionType = q.type;
            const isRequired = true; // 新接口中所有题目都是必填的
            // 类型显示文本
            let typeText = '';
            const t = String(questionType).toLowerCase();
            if (t === '1' || t === 'radio') typeText = '单选';
            else if (t === '2' || t === 'judge' || t === 'boolean') typeText = '判断';
            else if (t === '3' || t === 'checkbox') typeText = '多选';
            
            // 构建选项数组
            const options = [];
            const optionLabels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
            const optionFields = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
            
            optionFields.forEach((field, index) => {
                if (q[field] && q[field].trim()) {
                    options.push({
                        label: optionLabels[index],
                        value: q[field].trim()
                    });
                }
            });
            
            const wrap = document.createElement('div');
            wrap.className = 'question-item';
            wrap.setAttribute('data-qid', q.id);
            const isCheckbox = (t === '3' || t === 'checkbox');
            wrap.setAttribute('data-type', isCheckbox ? 'checkbox' : 'radio');
            wrap.setAttribute('data-required', '1');
            // 存储正确答案与分值用于评分
            wrap.setAttribute('data-correct', String((q.correctAnswer || q.answer || '')).toUpperCase());
            wrap.setAttribute('data-fraction', String(q.fraction || 0));
            
            // 题目标题（包含类型与分值）
            const titleHtml = `<div class="question-title">${idx + 1}. ${q.question || ''} ${typeText ? `<span class="question-type-tag">[${typeText}]</span>` : ''} <span class="question-fraction">(${q.fraction || 0}分)</span><span class="required-mark">*</span></div>`;
            
            let optionsHtml = '<div class="options-group">';
            if (isCheckbox) { // 多选
                options.forEach((opt, i) => {
                    const id = `q_${q.id}_${i}`;
                    optionsHtml += `<label class="option-item" for="${id}"><input id="${id}" type="checkbox" name="q_${q.id}" value="${opt.label}"><span>${opt.label}. ${opt.value}</span></label>`;
                });
            } else { // 单选或判断
                options.forEach((opt, i) => {
                    const id = `q_${q.id}_${i}`;
                    optionsHtml += `<label class="option-item" for="${id}"><input id="${id}" type="radio" name="q_${q.id}" value="${opt.label}"><span>${opt.label}. ${opt.value}</span></label>`;
                });
            }
            optionsHtml += '</div>';
            

            
            wrap.innerHTML = titleHtml + optionsHtml;
            container.appendChild(wrap);
        });

        // 进入详情后开始计时
        quizStartTimestamp = Date.now();

        container.addEventListener('change', onQuizAnswerChange, { once: true });
        container.addEventListener('change', onQuizAnswerChange);
        // 确保勾选复选框时能即时更新进度
        container.addEventListener('input', onQuizAnswerChange);
        const backBtn = document.getElementById('quiz-back-btn');
        if (backBtn) backBtn.onclick = () => { window.location.href = 'index.html'; };
        const cancelBtn = document.getElementById('quiz-cancel-btn');
        if (cancelBtn) cancelBtn.onclick = () => { window.location.href = 'index.html'; };
        const submitBtn = document.getElementById('quiz-submit-btn');
        if (submitBtn) submitBtn.onclick = validateAndSubmitQuiz;
    }

    function onQuizAnswerChange() {
        const container = document.getElementById('quiz-questions-container');
        if (!container) return;
        const items = Array.from(container.querySelectorAll('.question-item'));
        const total = items.length;
        const answered = items.reduce((acc, item) => {
            const qid = item.getAttribute('data-qid');
            const sel = container.querySelectorAll(`input[name="q_${qid}"]:checked`).length;
            return acc + (sel > 0 ? 1 : 0);
        }, 0);
        updateQuizProgress(answered, total);
    }

    function updateQuizProgress(answered, total) {
        const bar = document.getElementById('quiz-progress-bar');
        const text = document.getElementById('quiz-progress-text');
        const pct = total === 0 ? 0 : Math.round((answered / total) * 100);
        if (bar) bar.style.width = pct + '%';
        if (text) text.textContent = `${answered}/${total}`;
    }

    async function validateAndSubmitQuiz() {
        const container = document.getElementById('quiz-questions-container');
        const items = Array.from(container.querySelectorAll('.question-item'));
        // 必填校验
        for (const item of items) {
            const required = item.getAttribute('data-required') === '1';
            if (!required) continue;
            const qid = item.getAttribute('data-qid');
            const sel = container.querySelectorAll(`input[name="q_${qid}"]:checked`).length;
            if (sel === 0) {
                item.scrollIntoView({ behavior: 'smooth', block: 'center' });
                item.style.boxShadow = '0 0 0 2px rgba(255,77,79,0.3)';
                setTimeout(() => { item.style.boxShadow = 'none'; }, 1500);
                alert('请完成所有必填题');
                return;
            }
        }

        // 计算得分
        let totalScore = 0;
        let totalPossible = 0;
        items.forEach(item => {
            const qid = item.getAttribute('data-qid');
            const type = item.getAttribute('data-type'); // 'radio' | 'checkbox'
            const correctRaw = String(item.getAttribute('data-correct') || '').toUpperCase().replace(/\s+/g, '');
            const fraction = parseFloat(item.getAttribute('data-fraction') || '0') || 0;
            totalPossible += fraction;

            const checked = Array.from(container.querySelectorAll(`input[name="q_${qid}"]:checked`))
                .map(inp => String(inp.value).toUpperCase());

            if (type === 'checkbox') {
                // 多选：需要与正确答案完全一致（顺序无关）
                const selected = checked.sort().join('');
                const correct = correctRaw.split('').sort().join('');
                if (selected && selected === correct) {
                    totalScore += fraction;
                }
            } else {
                // 单选/判断：唯一选项与正确答案一致
                if (checked.length === 1 && checked[0] === correctRaw) {
                    totalScore += fraction;
                }
            }
        });

        // 计算用时（分 秒）
        const start = quizStartTimestamp || Date.now();
        const elapsedMs = Date.now() - start;
        const minutes = Math.floor(elapsedMs / 60000);
        const seconds = Math.floor((elapsedMs % 60000) / 1000);
        const timeText = `${minutes}分${seconds}秒`;

        // 组织提交负载
        const { userId, userName } = getUserInfo();
        const payload = {
            questionTypeId: currentQuestionTypeId,
            userId: userId,
            userName: userName,
            fraction: totalScore,
            timeConsuming: Math.round(elapsedMs / 1000)
        };

        const submitBtn = document.getElementById('quiz-submit-btn');
        if (submitBtn) submitBtn.disabled = true;

        try {
          console.log("---------------");
            console.log(payload);
            const resp = await fetch(API_BASE_URL + '/hr/dtQuestionResult/submit', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify(payload)
            });
            const resJson = await resp.json().catch(() => ({}));
            if (resp.ok && resJson && (resJson.success === true || resJson.code === 200)) {
                // 展示提交成功页面并倒计时返回
                const scoreEl = document.getElementById('success-score');
                const timeEl = document.getElementById('success-time');
                const cdEl = document.getElementById('success-countdown');
                if (scoreEl) scoreEl.textContent = `得分：${totalScore}分（满分${totalPossible}分）`;
                if (timeEl) timeEl.textContent = `用时：${timeText}`;
                showPage('quiz-success-page');

                let remain = 3;
                if (cdEl) cdEl.textContent = String(remain);
                const to = setInterval(() => {
                    remain -= 1;
                    if (cdEl) cdEl.textContent = String(remain);
                    if (remain <= 0) {
                        clearInterval(to);
                        // window.location.href = 'index.html#quiz';
                        window.location.href = 'index.html';
                    }
                }, 1000);

                const backBtn = document.getElementById('success-back-btn');
                if (backBtn) backBtn.onclick = () => {
                    // window.location.href = 'index.html#quiz';
                    window.location.href = 'index.html';
                };
            } else {
                const msg = (resJson && (resJson.message || resJson.msg)) || '未知错误';
                alert(`提交失败：${msg}\n\n本地得分：${totalScore}/${totalPossible}，用时：${timeText}`);
            }
        } catch (e) {
            alert(`提交异常：${e && e.message ? e.message : '网络异常'}\n\n本地得分：${totalScore}/${totalPossible}，用时：${timeText}`);
        } finally {
            if (submitBtn) submitBtn.disabled = false;
        }
    }

    function showPage(id) {
        const pages = document.querySelectorAll('.page-container');
        pages.forEach(p => { p.style.display = 'none'; p.classList.remove('active'); });
        const target = document.getElementById(id);
        if (target) { target.style.display = 'block'; target.classList.add('active'); }
    }
    </script>
</body>
</html>


